<template>
    <div class="video-main" :style="clientHeight">
            <div class="head-video">
                <div class="md-subhead">
                    <div class="maskLayer" v-if="maskLayer">{{broadcast}}</div>
                    <video id="videoOne" @click="playFn" :src="LivePath" :poster="LiveImg" autoplay type="video/mp4" x5-video-player-type='h5' x-webkit-airplay="true" x5-video-player-fullscreen='true' x5-playsinline="" webkit-playsinline="true" playsinline="true" style="object-fit:fill;width:100%;"></video>
                    <div class="playButton" v-if="myVideoPlayOne.paused && !maskLayer && LivePath ===former.LivePath" @click="videoHandlingFn"><div>▲</div></div>
                    <div :class="{'template':judgeTemplate}" class="judgeTemplate"><span>{{getTime}}</span><div>正在直播</div></div>
                </div>
            </div>
            <div class="cententBox">
                <div class="center">
                    <div class="left">
                        <p>{{livePersonDataNickname}}
                            <!-- <span class="attention1" v-if="!focusStatus && false" @click="addOn">+</span>
                            <span v-if="focusStatus && false" class="attention2" @click="addOn">+</span> -->
                        </p>
                    </div>
                    <div class="centent" style="text-align: center;">
                        <span :class="{'showColor':VideoPlayback}" @click="playback">回放</span>
                        <span :class="{'showColor':VideoStatus}" @click="VideoStatus=true;VideoPlayback=false;VideoChitchat=false;" v-if="false">状态</span>
                        <span :class="{'showColor':VideoChitchat}" @click="cutChitchat">聊天</span>
                    </div>
                    <div class="right">
                        <span class="onlineNumber">{{onlineNumber}}人在线</span>
                        <p>{{getDivision}}</p>
                    </div>
                </div>
            </div>
            <div class="footer" :style="footerHeight" style="overflow:auto;">
                <!-- 回放 -->
                <div class="playback" v-if="VideoPlayback">
                    <ul>
                        <li v-for="(item,index) in playbackDatar.list" :key="index" @click="cutVideoUrl(item.videoUrl, item.coverPath)">
                            <img :src="item.coverPath" alt="" style="height: 60px;">
                            <p class="playbackTime">{{item.duration}}</p>
                            <p class="playbackName">{{item.title}}</p>
                        </li>
                    </ul>
                </div>
                <!-- 状态 -->
                <div class="status" v-if="VideoStatus">
                    <ul>
                        <li v-for="(item,index) in 8" :key="index">
                            <p class="statusTime">19:50</p>
                            <span>00000</span>
                        </li>
                    </ul>
                </div>
                <!-- 聊天 -->
                <div class="chitchat" v-if="VideoChitchat">
                    <div class='chatBody'>
                        <div class='chatBox'>
                            <ul class="messageUl">
                                <li class='chatLi' v-for="(item, index) in dataArr" :key="index">
                                    <div class='chat' v-if="item.userId !==  userId && !item.judge">
                                        <div class='chatLeft position-r'>
                                            <div class='flex-box'>
                                                <img class='chatImg border-radius-50' :src='item.imgUrl'/>
                                                <div class='flex-1 chatContent'>
                                                    <div class="chatContent-box">
                                                    <em class='chatContentJt'></em>
                                                    <span class='text-align-j'><span class="chatContent-box-name">{{item.userName}}：</span>{{item.data}}</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    </div>
                                    <div class='chat' v-if="item.userId === userId && !item.judge">
                                        <div class='chatRight position-r'>
                                            <div class='flex-box'>
                                                <img class='chatImg border-radius-50' :src='item.imgUrl'/>
                                                <div class='flex-1 chatContent'>
                                                    <div class="chatContent-box">
                                                        <em class='chatContentJt'></em>
                                                        <span class='text-align-j'>{{item.data}}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </li>
                            </ul>
                        </div>
                        <div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
</template>
<script>
import apiDetail from '../../api/detail'
export default {
    data () {
        return {
            VideoPlayback: false,
            VideoStatus: false,
            VideoChitchat: true,
            clientHeight: 0,
            onlineNumber: 0,
            websocket: '',
            footerHeight: 0,
            userName: '',
            userImg: '',
            userId: '',
            getDivision: '',
            getTime: '',
            focusStatus: 0,
            livePersonDataNickname: '',
            livePersonData: '',
            ContinuePlay: false,
            myVideoPlayOne: {},
            myVideo:{},
            videoAmplification: false,
            playbackDatar: '',
            dataArr: [],
            SwitchVideo: '',
            getAccessTime: '',
            dataUserName: [],
            broadcastTime: '',
            maskLayer: false,
            judgeTemplate: true,
            lockReconnect: false, // 判断是否已经连接
            wsUrl: '', //websocket路径
            LivePath: '', // 直播路径
            LiveImg: '', // 直播图片
            former: '',
            heartTimeOut: '',
            overall: '',
            CurrentTime: '',
            judge: true,
            broadcast: '',
            judgeCount: 5
        }
    },
    mounted () {
        window.userInformation = this.userInformation
        window.sendMessage = this.sendMessage
        window.onbeforeunload =  () => {
            this.websocket.close()
        }
        this.initialize()
    },
    methods: {
        // 接收用户信息的方法
        userInformation (data) {
            data = JSON.parse(data);
            this.userName = data.userName // 用户名
            this.userImg = data.userImg // 用户头像
            this.userId = data.userId // 用户id
            // this.focus(this.userId)   //  获取是否关注当前直播人
        },
        //接收到消息的回调方法
        onMessage (data) {
            if (typeof data === 'number'){
                this.onlineNumber = data
            } else {
                this.dataArr.push(data)
            }
            clearTimeout(tt)
            var tt = setTimeout(() => {
                this.TalkDown()
            },1)
        },
        // 切换视频的方法
        cutVideoUrl (dataVedioUrl, dataVedioImg) {
            this.judgeTemplate = false
            this.myVideoPlayOne.controls = true
            this.LivePath = dataVedioUrl
            this.LiveImg = dataVedioImg
            this.maskLayer = false
        },
        // 打开页面默认初始化
        initialize () {
            this.dynamicGetTime()
            var nowTime = new Date().getTime()
            this.getTime = this.$timeCycle(nowTime, 'ymdhms')
            this.getDivision = this.$timeCycle(nowTime, 'ymdhms')
            var headVideo = document.getElementsByClassName('head-video')[0]
            var cententBox =  document.getElementsByClassName('cententBox')[0]
            var footer = document.getElementsByClassName('footer')[0]
            footer.style.height = document.body.clientHeight - headVideo.clientHeight - cententBox.clientHeight - 30 + 'px'
            this.clientHeight = 'height:'+ document.body.clientHeight + 'px;'
            apiDetail.myLiveParticulars({'id':this.$router.history.current.params.id}).then( res => {
                this.livePersonData = res.body.data
                this.livePersonDataNickname = this.livePersonData.userList[0].nickname
                this.wsUrl = 'ws://uat.ceiii.com.cn/common/chatRecordOneToMany/'+ this.livePersonData.pageInfo.roomId + '/' + this.livePersonData.pageInfo.userId
                this.createWebSocket()
                this.myVideoPlayOne = document.getElementById('videoOne')
                this.broadcastTime = this.livePersonData.pageInfo.beginTime
                this.videoHandlingFn()
            })
        },
        // 视频的处理方法
        videoHandlingFn () {
            this.CurrentTime = Math.ceil((new Date().getTime() - this.broadcastTime) / 1000)  // 当前时间 - 后台返回的时间 = 相差的时间
                if (this.CurrentTime > this.$timeTransverter(this.livePersonData.pageInfo.duration)) {  // 如果相差的时间 > 视频的时间总长  就是视频已经结束
                    this.maskLayer = true
                    this.broadcast = '直播已结束'
                } else if (this.CurrentTime < 0){   // 如果是负数那就是还未到直播时间
                    this.maskLayer = true
                    this.broadcast = '该直播将于  ' + this.$timeCycle(this.broadcastTime, 'ymdhms') + '  开始'
                } else {   // 如果既不大于视频的总长又不是负数那就是当前在直播的时间内
                    this.LivePath = this.livePersonData.pageInfo.videoUrl
                    this.LiveImg = this.livePersonData.pageInfo.coverPath
                    this.former = {'LivePath': this.LivePath, 'LiveImg': this.LiveImg}
                    this.myVideoPlayOne.currentTime = this.CurrentTime
                    this.maskLayer = false
                    this.judge = false
                    clearTimeout(tt)
                    var tt = setTimeout(() => {
                        this.myVideoPlayOne.play()
                    },1)
                }
                this.myVideoPlayOne.addEventListener("ended", () => {
                    if (this.former.LivePath === this.LivePath) {
                        this.maskLayer = true
                        this.LivePath = ''
                        this.LiveImg = ''
                        this.broadcast = '直播已结束'
                        this.former = {'LivePath': '', 'LiveImg': ''}
                    }
            })
        },
        // 点击播放
        playFn () {
            if (this.VideoChitchat && this.myVideoPlayOne.paused) { // 判断是否在直播状态和是否已经在播放了,已经在播放就是false，就不能点击屏幕了
                this.videoHandlingFn()
            }
        },
        // 判断是否关注
        // focus(attentionId){
        //     let parms = {'userId':this.$router.history.current.params.userId, 'attentionId':attentionId}
        //     apiDetail.focusOn(parms).then(data => {
        //         this.focusStatus = data.body.data.focusStatus
        //     })
        // },
        // 点击关注
        // addOn(){
        //     if (this.userId) {
        //         let parms = {userId:this.livePersonData.pageInfo.userId, attentionId:this.userId, focusStatus:this.focusStatus}
        //         apiDetail.addFocus(parms).then(data => {
        //             this.focusStatus = data.body.data.focusStatus
        //         })
        //     } else {
        //         if (this.$isAndroid) {
        //             window.android.isLogin()
        //         } else if(this.$isiOS) {
        //             window.webkit.messageHandlers.isLogin.postMessage('')
        //         }
        //     }
        // },
        // 切换回直播
        cutChitchat () {
            this.VideoChitchat=true
            this.VideoPlayback=false
            this.VideoStatus=false
            this.judgeTemplate = true
            this.myVideoPlayOne.controls = false
            if (this.former.LivePath) {
                this.LivePath = this.former.LivePath
                clearTimeout(tt)
                var tt = setTimeout(() => {
                        this.myVideoPlayOne.currentTime = Math.ceil((new Date().getTime() - this.broadcastTime) / 1000)
                },1000)
            } else if (new Date().getTime() < this.broadcastTime) {
                this.maskLayer = true
                this.LivePath = ''
                this.LiveImg = ''
                this.broadcast = '该直播将于  ' + this.$timeCycle(this.broadcastTime, 'ymdhms') + '  开始'
            } else if (new Date().getTime() > this.broadcastTime) {
                this.LivePath = ''
                this.LiveImg = ''
                this.maskLayer = true
                this.broadcast = '直播已结束'
            }
        },
        // 动态获取实时时间方法
        dynamicGetTime () {
            clearTimeout(tt)
            var tt = setTimeout(() => {
                var nowTime = new Date().getTime()
                this.getTime = this.$timeCycle(nowTime, 'ymdhms')
                this.getDivision = this.$timeCycle(nowTime, 'ymdhms')
                this.dynamicGetTime()
                if (this.broadcastTime === Math.floor(nowTime / 1000) * 1000 && this.judge) {  // 直播开始的时间 === 当前时间     判断是否到直播时间
                    this.LivePath = this.livePersonData.pageInfo.videoUrl
                    this.LiveImg = this.livePersonData.pageInfo.coverPath
                    this.former = {'LivePath': this.LivePath, 'LiveImg': this.LiveImg}
                    this.cutChitchat()
                    this.maskLayer = false
                    this.judge = false
                }
            },1000)
        },
        // 回放
        playback () {
            this.VideoPlayback=true;
            this.VideoStatus=false;
            this.VideoChitchat=false;
            if (this.playbackDatar === '') {
                apiDetail.myPlayback({'pageNum':1000, 'pageSize': 2000}).then( res => {
                    this.playbackDatar = res.data.data
                })
            }
        },
        //发送消息
        sendMessage (data) {
            if (this.userImg) {
                this.cutChitchat()
                this.myVideoPlayOne.controls = false
                this.websocket.send(JSON.stringify({'data':data, 'userId':this.userId, 'imgUrl':this.userImg, 'userName':this.userName}))
                this.TalkDown()
            }
        },
        // 聊天置底方法
        TalkDown () {
            var footer = document.getElementsByClassName('footer')[0]
            footer.scrollTop = footer.scrollHeight
        },
        // WebSocket初始化方法
        createWebSocket() {
            try {
                this.websocket = new WebSocket(this.wsUrl);
                this.WebSocketiInit()
            } catch(e) {
                this.reconnect(this.wsUrl);
            }
        },
        // webSocket初始化
        WebSocketiInit () {
            this.websocket.onclose = () => {
                console.log('连接关闭')
                this.reconnect(this.wsUrl);
            };
            this.websocket.onerror = (evt) => {
                console.log('发生异常了')
                this.reconnect(this.wsUrl)
            };
            this.websocket.onopen = () => {
                console.log('连接成功')
            };
            this.websocket.onmessage = (data) => {
                //拿到任何消息都说明当前连接是正常的
                this.overall = JSON.parse(data.data)
                this.onMessage(this.overall)
            }
        },
        // 重连操作 reconnect
        reconnect(url) {
            if(this.lockReconnect) {
                return;
            };
            this.lockReconnect = true;
            //没连接上会一直重连，设置延迟避免请求过多
            if (this.judgeCount) {
                clearTimeout(tt);
                var tt = setTimeout(() => {
                    this.judgeCount--
                    this.createWebSocket(url);
                    this.lockReconnect = false;
                }, 5000);
            }
        }
    }
}
</script>